var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var app = getApp();

Page({
  data: {
    isMultiOrderModel: 0,
    cartGoods: [],
    checkedGoodsCount: 0,
    checkedGoodsAmount: 0.00,
    isEditCart: false,
    checkedAllStatus: true,
    editCartList: [],
    hasLogin: false,
    fukucunsale: true,
    page: 1,
    limit: 10
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady: function () {
    // 页面渲染完成
  },
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getCartList();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  onShow: function () {
    // 页面显示
    this.setData({
      page: 1,
      cartGoods: []
    });
    this.getCartList();
    user.getcartgoodnum().then(res => {
      var cartnum = res.data.icount + '';
      wx.setStorageSync('cartnum', cartnum);
      wx.setTabBarBadge({
        index: 2,
        text: cartnum
      })
    });
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  getCartList: function () {
    let that = this;
    util.request(api.ShoppingCartList, {
      page: that.data.page,
      limit: that.data.limit
    }).then(function (res) {
      if (res.result == 1) {
        if (res.data.shoppingcartList.length > 0) {
          that.setData({
            cartGoods: that.data.cartGoods.concat(res.data.shoppingcartList),
            page: that.data.page + 1,
          });
        }
        that.setData({
          fukucunsale: res.data.fukucunsale,
          checkedAllStatus: that.isCheckedAll(),
          checkedGoodsCount: that.getCheckedGoodsCount(),
          checkedGoodsAmount: that.getCheckedGoodsAmount()
        });
      }
    });
  },
  isChildCheckedAll: function (cartList) {
    return cartList.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  isCheckedAll: function () {
    let that = this;
    return that.data.cartGoods.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  doCheckedAll: function (checkedAllStatus) {
    let that = this;
    var _cartGoods = that.data.cartGoods;
    for (let i = 0; i < _cartGoods.length; i++) {
      if (checkedAllStatus) {
        _cartGoods[i].checked = ''
      } else {
        _cartGoods[i].checked = true
      }
    }
    that.setData({
      cartGoods: _cartGoods
    });
    return true;
  },
  getProductChecked: function (goodsid) {
    let that = this;
    let isChecked = null;
    var _cartGoods = that.data.cartGoods;
    for (let i = 0; i < _cartGoods.length; i++) {
      if (_cartGoods[i].id == goodsid) {

        if (_cartGoods[i].checked) {
          _cartGoods[i].checked = '',
            isChecked = false
        } else {
          _cartGoods[i].checked = true
          isChecked = true
        }
      }
    }
    that.setData({
      cartGoods: _cartGoods
    });
    return isChecked;
  },
  checkedItem: function (event) {
    let goodsid = event.currentTarget.dataset.goodsid;
    let that = this;
    let isChecked = that.getProductChecked(goodsid);

    //非编辑状态
    if (!this.data.isEditCart) {
      util.request(api.ShoppingCartChecked, {
        cartidarr: goodsid,
        checked: isChecked
      }, 'POST').then(function (res) {
        if (res.result == 1) {
          console.log("checkedItem");
        }
      });
      that.setData({
        checkedAllStatus: that.isCheckedAll(),
        checkedGoodsCount: that.getCheckedGoodsCount(),
        checkedGoodsAmount: that.getCheckedGoodsAmount()
      });
    } else {
      //编辑状态
      that.setData({
        checkedAllStatus: that.isCheckedAll(),
        checkedGoodsCount: that.getCheckedGoodsCount(),
        checkedGoodsAmount: that.getCheckedGoodsAmount()
      });
    }
  },
  getCheckedGoodsCount: function () {
    let that = this;
    let checkedGoodsCount = 0;
    that.data.cartGoods.forEach(function (v) {
      if (v.checked) {
        checkedGoodsCount += 1;
      }
    });
    return checkedGoodsCount;
  },
  getCheckedGoodsAmount: function () {
    let that = this;
    let checkedGoodsAmount = 0.00;

    that.data.cartGoods.forEach(function (v) {
      if (v.checked) {
        checkedGoodsAmount += v.xiaoshoujia * v.number;
      }
    });
    return checkedGoodsAmount;
  },
  checkedAll: function () {
    let that = this;
    if (!this.data.isEditCart) {
      let cartidarr = [];
      that.data.cartGoods.forEach(function (v) {
        cartidarr.push(v.id);
      });
      util.request(api.ShoppingCartChecked, {
        cartidarr: cartidarr.toString(),
        checked: !that.data.checkedAllStatus
      }, 'POST').then(function (res) {
        if (res.result == 1) {
          console.log("ok");
        }
      });
      if (that.doCheckedAll(that.data.checkedAllStatus)) {
        that.setData({
          checkedAllStatus: that.isCheckedAll(),
          checkedGoodsCount: that.getCheckedGoodsCount(),
          checkedGoodsAmount: that.getCheckedGoodsAmount()
        });
        that.setData({
          checkedAllStatus: that.isCheckedAll(),
          checkedGoodsCount: that.getCheckedGoodsCount(),
          checkedGoodsAmount: that.getCheckedGoodsAmount()
        });
      }
    } else {
      //编辑状态,将所有
      let checkedAllStatus = that.isCheckedAll();
      if (that.data.isMultiOrderModel === 1) {
        let tmpBrandCartData = this.data.brandCartgoods.map(function (element, index, array) {
          let tmpBrandGoods = element.cartList.map(function (childEle, childIndex, childArr) {
            childEle.checked = !checkedAllStatus;
            return childEle;
          });
          element.cartList = tmpBrandGoods;
          return element;
        });

        that.setData({
          brandCartgoods: tmpBrandCartData,
          checkedAllStatus: that.isCheckedAll(),
          checkedGoodsCount: that.getCheckedGoodsCount()
        });
      } else {
        let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
          element.checked = !checkedAllStatus;
          return element;
        });

        that.setData({
          cartGoods: tmpCartData,
          checkedAllStatus: that.isCheckedAll(),
          checkedGoodsCount: that.getCheckedGoodsCount()
        });
      }
    }
  },
  editCart: function () {
    var that = this;
    if (this.data.isEditCart) {
      this.setData({
        page: 1,
        cartGoods: []
      });
      this.getCartList();
      this.setData({
        isEditCart: !this.data.isEditCart
      });
    } else {
      //编辑状态
      let tmpCartData = that.data.cartGoods.map(function (element, index, array) {
        element.checked = false;
        return element;
      });
      that.setData({
        cartGoods: tmpCartData,
        isEditCart: !that.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        checkedGoodsCount: that.getCheckedGoodsCount()
      });
    }
  },

  updateCart: function (cartId, number) {
    let that = this;
    util.request(api.ShoppingCartUpdate, {
      id: cartId,
      number: number
    }, 'POST').then(function (res) {
      console.log("checkedItem");
    });

  },
  getProductItem: function (cartid) {
    let that = this;
    let cartItem = null;
    that.data.cartGoods.forEach(function (o) {
      if (o.id === cartid) {
        cartItem = o;
      }
    });
    return cartItem;
  },
  setProductItem: function (cartItem, cartid) {
    let that = this;
    let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
      if (element.id === cartid) {
        return cartItem;
      } else {
        return element;
      }
    });
    that.setData({
      cartGoods: tmpCartData,
      checkedAllStatus: that.isCheckedAll(),
      checkedGoodsCount: that.getCheckedGoodsCount()
    });
  },
  cutNumber: function (event) {
    let cartid = event.currentTarget.dataset.cartid;
    let cartItem = this.getProductItem(cartid);
    let number = (cartItem.number - 1 > 1) ? cartItem.number - 1 : 1;
    cartItem.number = number;
    this.setProductItem(cartItem, cartid);
    this.updateCart(cartid, number);
  },
  addNumber: function (event) {
    let cartid = event.currentTarget.dataset.cartid;
    let cartItem = this.getProductItem(cartid);

    let number = cartItem.number + 1;
    cartItem.number = number;
    this.setProductItem(cartItem, cartid);
    this.updateCart(cartid, number);
  },
  palceorder: function () {
    //获取已选择的商品
    let that = this;
    if (that.getCheckedGoodsCount() <= 0) {
      wx.showModal({
        title: '错误信息',
        content: '请勾选需要下单的商品！',
        showCancel: false
      });
      return false;
    }

    // storage中设置了shoppingcartid，则是购物车购买
    try {
      wx.setStorageSync('shoppingcartid', '');
      wx.navigateTo({
        url: '/pages/order/order'
      })
    } catch (e) {}

  },
  deleteCart: function () {
    //获取已选择的商品
    let that = this;
    if (that.getCheckedGoodsCount() <= 0) {
      wx.showModal({
        title: '错误信息',
        content: '请勾选需要删除的商品！',
        showCancel: false
      });
      return false;
    }
    let cartidarr = [];
    let _cartGoods = that.data.cartGoods;
    for (let i = 0; i < _cartGoods.length; i++) {
      if (_cartGoods[i].checked) {
        cartidarr.push(_cartGoods[i].id);
        _cartGoods.splice(i, 1);
        i--;
      }
    }
    util.request(api.ShoppingCartDelete, {
      cartidarr: cartidarr.toString()
    }, 'POST').then(function (res) {
      if (res.result == 1) {
        that.setData({
          cartGoods: _cartGoods
        });
        var _cartnum = _cartGoods.length + '';
        wx.setStorageSync('cartnum', _cartnum);
        wx.setTabBarBadge({
          index: 2,
          text: _cartnum
        })
      }
    });
  }
})